package com.hs.auth.service.impl;

import com.hs.auth.form.RegisterBody;
import com.hs.auth.service.LoginService;
import com.hs.common.captcha.config.properties.RegisterProperties;
import com.hs.common.captcha.service.ValidateCodeService;
import com.hs.common.core.constant.CacheConstants;
import com.hs.common.core.constant.Constants;
import com.hs.common.core.constant.SecurityConstants;
import com.hs.common.core.domain.Result;
import com.hs.common.core.enums.UserStatus;
import com.hs.common.core.exception.ServiceException;
import com.hs.common.core.text.Convert;
import com.hs.common.core.utils.StringUtils;
import com.hs.common.core.utils.ip.IpUtils;
import com.hs.common.core.web.domain.AjaxResult;
import com.hs.common.email.MailService;
import com.hs.common.redis.service.RedisService;
import com.hs.common.security.utils.SecurityUtils;
import com.hs.system.api.feign.RemoteSystemService;
import com.hs.system.api.entity.User;
import com.hs.system.api.model.LoginUser;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.hs.common.core.constant.UserConstants.*;

/**
 * 登录校验方法
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Resource
    private RemoteSystemService remoteSystemService;

    @Resource
    private PasswordServiceImpl passwordService;

    @Resource
    private LogServiceImpl logService;

    @Resource
    private RedisService redisService;

    @Resource
    private MailService mailService;

    @Resource
    private ValidateCodeService validateCodeService;

    @Resource
    private RegisterProperties registerProperties;

    /**
     * 登录
     */
    public LoginUser login(String email, String password) {
        // 用户名或密码为空 错误
        System.out.println("email=" + email);
        System.out.println("password=" + password);
        if (StringUtils.isAnyBlank(email, password)) {
            logService.recordLoginInfo(email, Constants.LOGIN_FAIL, "邮箱/密码必须填写");
            throw new ServiceException("邮箱/密码必须填写");
        }
        if (!EmailValidator.getInstance().isValid(email)) {
            throw new ServiceException("邮箱格式错误");
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < PASSWORD_MIN_LENGTH
                || password.length() > PASSWORD_MAX_LENGTH) {
            logService.recordLoginInfo(email, Constants.LOGIN_FAIL, "用户密码不在指定范围");
            throw new ServiceException("用户密码不在指定范围");
        }
//        // 用户名不在指定范围内 错误
//        if (email.length() < UserConstants.USERNAME_MIN_LENGTH
//                || email.length() > USERNAME_MAX_LENGTH) {
//            logService.recordLoginInfo(email, Constants.LOGIN_FAIL, "用户名不在指定范围");
//            throw new ServiceException("用户名不在指定范围");
//        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            logService.recordLoginInfo(email, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        Result<LoginUser> userResult = remoteSystemService.getUserInfo(email, SecurityConstants.INNER);

        if (userResult.getCode() == Constants.FAIL) {
            throw new ServiceException(userResult.getMsg());
        }

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            logService.recordLoginInfo(email, Constants.LOGIN_FAIL, "登录用户不存在");
            throw new ServiceException("登录用户：" + email + " 不存在");
        }

        if (Result.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        User user = userResult.getData().getUser();
        if (UserStatus.DELETED.getCode().equals(user.getStatus())) {
            logService.recordLoginInfo(email, Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + email + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            logService.recordLoginInfo(email, Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + email + " 已停用");
        }
        passwordService.validate(user, password);
        logService.recordLoginInfo(email, Constants.LOGIN_SUCCESS, "登录成功");
        return userInfo;
    }

    public String logout(String email) {
        logService.recordLoginInfo(email, Constants.LOGOUT, "退出成功");
        return "退出成功";
    }

    /**
     * 注册
     */
    public String register(RegisterBody registerBody) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(getBodyEmail(registerBody), registerBody.getPassword())) {
            throw new ServiceException("邮箱/密码必须填写");
        }
        if (!EmailValidator.getInstance().isValid(registerBody.getEmail())) {
            throw new ServiceException("邮箱格式错误");
        }
//        if (username.length() < USERNAME_MIN_LENGTH
//                || username.length() > USERNAME_MAX_LENGTH) {
//            throw new ServiceException(USERNAME_NOTE);
//        }
        if (registerBody.getPassword().length() < PASSWORD_MIN_LENGTH
                || registerBody.getPassword().length() > PASSWORD_MAX_LENGTH) {
            throw new ServiceException(PASSWORD_NOTE);
        }

        Result<LoginUser> userInfo = remoteSystemService.getUserInfo(registerBody.getEmail(), SecurityConstants.INNER);
        System.out.println("userInfo=" + userInfo);
        if (userInfo.getData() != null) {
            throw new ServiceException("该邮箱已注册");
        }

        //校验验证码
        validateCodeService.checkCaptchaNum(registerBody.getCode(), registerBody.getUuid());

        // 注册用户信息
        User user = new User();
        user.setEmail(registerBody.getEmail());
        user.setPassword(SecurityUtils.encryptPassword(registerBody.getPassword()));
        Result<?> registerResult = remoteSystemService.registerUserInfo(user, SecurityConstants.INNER);

        if (Result.FAIL == registerResult.getCode()) {
            throw new ServiceException(registerResult.getMsg());
        }
//        logService.recordLoginInfo(username, Constants.REGISTER, "注册成功");
        return "注册成功";
    }

    private static String getBodyEmail(RegisterBody registerBody) {
        return registerBody.getEmail();
    }

    @Override
    public AjaxResult getCodeEmail(String email) {
        RegisterProperties.Email emailConfig = registerProperties.getEmail();
        RegisterProperties.Captcha captchaConfig = emailConfig.getCaptcha();
        if (StringUtils.isEmpty(email)) {
            throw new ServiceException("收件邮箱不能为空");
        }
        if (!EmailValidator.getInstance().isValid(email)) {
            throw new ServiceException("邮箱格式错误");
        }
        AjaxResult captchaResult = validateCodeService.getNumberCaptcha();
        String uuid = (String) captchaResult.get("uuid");
        String captcha = (String) captchaResult.get("captcha");
        long expiration = (long) captchaResult.get("expiration");
        String content = emailConfig.getContent1() + captcha + emailConfig.getContent2() + captchaConfig.getExpiration() + emailConfig.getContent3();

        mailService.sendSimpleText(email, emailConfig.getSubject(), content);
        AjaxResult data = new AjaxResult();
        data.put("uuid", uuid);
        data.put("expiration", expiration);
        return AjaxResult.success("验证码获取成功", data);
    }
}
